import { getToken, setToken, removeToken, setTimeStamp } from '@/utils/auth'
import { login, getUserInfo, getUserInfoId } from '@/api/user'
export default {
  namespaced: true,
  state: {
    token: getToken(),
    userInfo: {}
  },
  mutations: {
    mySetToken(state, token) {
      state.token = token
      setToken(token)
    },
    myRemoveToken(state) {
      state.token = null
      removeToken()
    },
    setUserInfo(state, userinfo) {
      state.userInfo = userinfo
    },
    removeUserInfo(state) {
      state.userInfo = {}
    }
  },
  actions: {
    async login(context, payload) {
      const res = await login(payload)

      context.commit('mySetToken', res)
      setTimeStamp()
    },
    async getUserInfo(context) {
      const result = await getUserInfo()
      const reResult = await getUserInfoId(result.userId)
      const obj = { ...result, ...reResult }
      context.commit('setUserInfo', obj)
    },
    logout(context) {
      context.commit('myRemoveToken')
      context.commit('removeUserInfo')
    }
  }
}
